//
//  GYSearchResultViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/7.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYSearchResultViewController.h"
#import "GYSortView.h"
#import "GYNetWorkTools.h"
#import "GYSearchGoos.h"
#import "GYHorGoodsCell.h"
#import "GYVerGoodsCell.h"
#import "GYNoAddressView.h"
#import "GYButton.h"
#import "GYShopHomeViewController.h"
#import "GYBasePopoverViewController.h"
#import "PopoverAnimation.h"
#import "GYSystemMessageViewController.h"
#import "GYUser.h"
#import "GYShopingCartViewController.h"

static NSString *VCellIdentifier = @"VCellIdentifier";
static NSString *HCellIdentifier = @"HCellIdentifier";

@interface GYSearchResultViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>

@property (weak, nonatomic) IBOutlet UIButton *multBtu;

@property (weak, nonatomic) IBOutlet UIButton *salesBtu;

@property (weak, nonatomic) IBOutlet UICollectionView *goodsCollectionView;

/** 排序图 */
@property (nonatomic, strong) GYSortView *sortView;

/** 商品显示列表 */
@property (nonatomic, strong) NSMutableArray *goodsList;

@property (nonatomic, getter=isLayout) BOOL layout;

/** 搜索结果为空的界面 */
@property (nonatomic, strong) GYNoAddressView *searchInfoView;

/** 动画代理 */
@property (nonatomic, strong) PopoverAnimation *animationDelegate;

/** 缓存cell的高度 */
@property (nonatomic, strong) NSMutableDictionary *cachesHeight;
@end

@implementation GYSearchResultViewController


- (IBAction)onClick:(UIButton *)sender {
    switch (sender.tag) {
        case 1:
        {
            if (self.sortView != nil) {
                self.sortView.hidden = !self.sortView.isHidden;
            }else {
                self.sortView = [[[NSBundle mainBundle] loadNibNamed:@"GYSortView" owner:nil options:nil] firstObject];
                self.sortView.frame = CGRectMake(0, 50, ScreenWidth, ScreenHeight-64-50);
                [self.view addSubview:self.sortView];
            }
            __weak typeof(self) weakSelf = self;
            self.sortView.sortResultCallBack = ^(NSInteger tag,NSString *sortTitle) {
                //1.隐藏视图
                weakSelf.sortView.hidden = YES;
                [weakSelf.multBtu setTitle:sortTitle forState:UIControlStateNormal];
                //这里决定这个商品是怎么样排序的;
                switch (tag) {
                    case 0:
                    {
                        [weakSelf loadSearchGoodsData:weakSelf.gc_id keyword:weakSelf.currentSearchTitle page:@"" curpage:@"" key:@"" order:@""];
                    }
                        break;
                    
                    case 1:
                    {
                        [weakSelf loadSearchGoodsData:weakSelf.gc_id keyword:weakSelf.currentSearchTitle page:@"" curpage:@"" key:@"3" order:@"2"];
                    }
                        break;
                        
                    case 2:
                    {
                        [weakSelf loadSearchGoodsData:weakSelf.gc_id keyword:weakSelf.currentSearchTitle page:@"" curpage:@"" key:@"3" order:@"1"];
                    }
                        break;
                        
                    case 3:
                    {
                        [weakSelf loadSearchGoodsData:weakSelf.gc_id keyword:weakSelf.currentSearchTitle page:@"" curpage:@"" key:@"2" order:@"2"];
                    }
                        break;
                    default:
                        break;
                }
            };
            
            [self.multBtu setTitleColor:RGBColor(15, 206, 194) forState:UIControlStateNormal];
            [self.salesBtu setTitleColor:RGBColor(137, 137, 137) forState:UIControlStateNormal];
        }
            break;
            
        case 2:
        {
            self.sortView.hidden = YES;
            [self.salesBtu setTitleColor:RGBColor(15, 206, 194) forState:UIControlStateNormal];
            [self.multBtu setTitleColor:RGBColor(137, 137, 137) forState:UIControlStateNormal];
            
            //要把商品进行销量优先排行
            [self loadSearchGoodsData:@"" keyword:self.currentSearchTitle page:@"" curpage:@"" key:@"1" order:@"2"];
        }
            break;
            
        case 3:
        {
            NSLog(@"不同显示方式按钮");
            sender.selected = !sender.selected;
            self.layout = sender.selected;
            [self.goodsCollectionView reloadData];
        }
            break;
            
        default:
            break;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化
    [self setupUI];
}

- (void)setupUI {
    //1.设置开始布局 为横向布局
    self.layout = NO;
    
    //2.设置collectionView的基础属性
    self.goodsCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 10, 0);
    [self.goodsCollectionView registerNib:[UINib nibWithNibName:@"GYHorGoodsCell" bundle:nil] forCellWithReuseIdentifier:HCellIdentifier];
    [self.goodsCollectionView registerNib:[UINib nibWithNibName:@"GYVerGoodsCell" bundle:nil] forCellWithReuseIdentifier:VCellIdentifier];
    
    //3.设置搜索框
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, 130, 40);
    searchBar.backgroundImage = [[UIImage alloc] init];
    UITextField *searchField = [searchBar valueForKey:@"searchField"];
    searchField.layer.borderColor = RGBColor(152, 152, 152).CGColor;
    searchBar.placeholder = @"请输入关键词";
    self.navigationItem.titleView = searchBar;
    
    //3.1设置导航栏
    //UIBarButtonItem *cateItem = [UIBarButtonItem itemWithImage:@"stiore_categroy_b" tagret:self action:@selector(categoryBtuClick) button:nil];
    UIBarButtonItem *moreItem = [UIBarButtonItem itemWithImage:@"more_b" tagret:self action:@selector(moreBtuClick) button:nil];
    self.navigationItem.rightBarButtonItems = @[moreItem];
    
    //4.根据关键词加载数据
    [self loadSearchGoodsData:self.gc_id keyword:self.currentSearchTitle page:@"" curpage:@"" key:@"" order:@""];
}

//- (void)categoryBtuClick {
//    self.tabBarController.selectedIndex = 1;
//}

- (void)moreBtuClick {
    GYBasePopoverViewController *basePopoverVC = [[GYBasePopoverViewController alloc] initWithNibName:@"GYBasePopoverViewController" bundle:nil];
    __weak typeof(self) weakSelf = self;
    basePopoverVC.popoverViewSelectIndexCallBack = ^(NSInteger index) {
        switch (index) {
            case 0:
            {
                weakSelf.tabBarController.selectedIndex = 0;
                [weakSelf.tabBarController.tabBar setHidden:NO];
            }
                break;
                
            case 1:
            {
                if ([GYUser loadUserInfo] != nil) {
                    GYShopingCartViewController *shopingCartVC = [[GYShopingCartViewController alloc] initWithNibName:@"GYShopingCartViewController" bundle:nil];
                    [weakSelf.navigationController pushViewController:shopingCartVC animated:YES];
                }else {
                    weakSelf.tabBarController.selectedIndex = 2;
                }
            }
                break;
                
            case 2:
            {
                weakSelf.tabBarController.selectedIndex = 2;
            }
                break;
                
            case 3:
            {
                NSLog(@"消息....");
                if ([GYUser loadUserInfo] != nil) {
                    GYSystemMessageViewController *systemMessageVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
                    [weakSelf.navigationController pushViewController:systemMessageVC animated:YES];
                    
                }else {
                    weakSelf.tabBarController.selectedIndex = 2;
                }

            }
                break;
                
            default:
                break;
        }
    };
    basePopoverVC.titles = @[@"首页",@"购物车",@"我的商城",@"消息"];
    basePopoverVC.images = @[@"home_w",@"ff_icon3",@"ff_icon4",@"message_w"];
    
    self.animationDelegate = [[PopoverAnimation alloc] init];
    self.animationDelegate.popoverFrame = CGRectMake(ScreenWidth-widthScale(130, iphone6_W)-5, 50, widthScale(130, iphone6_W), basePopoverVC.titles.count*50);
    basePopoverVC.transitioningDelegate = (id)weakSelf.animationDelegate;
    
    basePopoverVC.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:basePopoverVC animated:YES completion:nil];

}
//加载搜索结果
- (void)loadSearchGoodsData:(NSString *)gc_id keyword:(NSString *)keyword page:(NSString *)page curpage:(NSString *)curpage key:(NSString *)key order:(NSString *)order{
    [GYNetWorkTools requestGoodList:gc_id keyword:keyword page:page curpage:curpage key:key order:order success:^(NSDictionary *obj) {
        int code = [[obj objectForKey:@"code"] intValue];
        if (code == 200) {
            NSDictionary *datas = [obj objectForKey:@"datas"];
            NSArray *goods_list = [datas objectForKey:@"goods_list"];
            //这里判断数据有没有
            if (goods_list.count == 0) {
                //显示没有商品的界面
                if (self.searchInfoView) {
                    self.searchInfoView.hidden = NO;
                }else {
                    [self creatNoSearchResultInfoView];
                }
            }else {
                self.searchInfoView.hidden = YES;
                [self.goodsList removeAllObjects];
                for (NSDictionary *dic in goods_list) {
                    GYSearchGoos *goods = [[GYSearchGoos alloc] initWithDic:dic];
                    [self.goodsList addObject:goods];
                }
                [self.goodsCollectionView reloadData];
            }
        }
    } error:^(NSError *error) {
        
    }];
}

//创建没有搜索结果的UI
- (void)creatNoSearchResultInfoView {
    GYNoAddressView *searchInfoView = [[[NSBundle mainBundle]loadNibNamed:@"GYNoAddressView" owner:nil options:nil]firstObject];
    searchInfoView.frame = CGRectMake(0, 50, ScreenWidth, ScreenHeight-64-50);
    searchInfoView.markImageView.image = [UIImage imageNamed:@"search_w"];
    searchInfoView.headLable.text = @"没有找到任何相关信息";
    searchInfoView.footLable.text = @"选择搜索其他商品分类/名称...";
    [searchInfoView.addBtu setTitle:@"重新选择" forState:UIControlStateNormal];
    __weak typeof(self) weakSelf = self;
    searchInfoView.addNewAddressCallBack = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    [self.view addSubview:searchInfoView];
    self.searchInfoView = searchInfoView;
}

#pragma mark -- UISearchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.goodsList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.layout) {
        GYVerGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:VCellIdentifier forIndexPath:indexPath];
        cell.model = self.goodsList[indexPath.item];
        
        return cell;
    }else {
        GYHorGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HCellIdentifier forIndexPath:indexPath];
        cell.model = self.goodsList[indexPath.item];
        
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GYSearchGoos *goods = self.goodsList[indexPath.item];
    GYShopHomeViewController *shopHomeControlelr = [[GYShopHomeViewController alloc] init];
    shopHomeControlelr.goods_id = goods.goods_id;
    [self.navigationController pushViewController:shopHomeControlelr animated:YES];
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    GYSearchGoos *good = self.goodsList[indexPath.item];
    if (self.layout) {
        //GYVerGoodsCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"GYVerGoodsCell" owner:nil options:nil]firstObject];
        CGFloat height = [[self.cachesHeight objectForKey:good.goods_id] floatValue];
        if (height != 0) {
            return CGSizeMake((ScreenWidth-5)/2, height);
        }else {
            CGFloat nameHeight = [good.goods_name boundingRectWithSize:CGSizeMake((ScreenWidth-5)/2, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
            CGFloat rowHeight = (ScreenWidth-5)/2+nameHeight+65;
            [self.cachesHeight setObject:@(rowHeight) forKey:good.goods_id];
            
            return CGSizeMake((ScreenWidth-5)/2, rowHeight);
        }
    }else {
        
        GYHorGoodsCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"GYHorGoodsCell" owner:nil options:nil]firstObject];
        
        return CGSizeMake(ScreenWidth, [cell cellHeight:good]);
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.layout ? 5 :0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.layout ? 5 :0;
}


#pragma mark -- 懒加载

- (NSMutableArray *)goodsList {
    if (!_goodsList) {
        _goodsList = [NSMutableArray array];
    }
    
    return _goodsList;
}

- (NSMutableDictionary *)cachesHeight {
    if (!_cachesHeight) {
        _cachesHeight = [NSMutableDictionary dictionary];
    }
    
    return _cachesHeight;
}
@end
